<template>
  <video
    :id="idName"
    autoplay
    controls
    muted
    playsinline
    controlslist="nodownload noplaybackrate"
    width="100%"
    :height="height"
  ></video>
</template>
<script>
import flvjs from "flv.js";
export default {
  name: "flvRoomRobot",
  data() {
    return {
      flvPlayer: null,
      flvTimer: null,
      flvListener: null,
      lastDecodedFrame: 0,
    };
  },
  props: {
    idName: {
      type: String,
      required: true,
    },
    roomId: {
      required: true,
    },
    // isTalkBack: {
    //   type: Boolean,
    // },
    height: {
      type: Number,
    },
  },
  mounted() {
    console.log(this.idName);
    this.videoUrl = `/live?port=1935&app=live&stream=${this.roomId}`;
    this.createVideo(this.videoUrl, this.idName);
    this.onError();
    this.onInfo();
    this.setTime();
    this.setListener();
  },
  methods: {
    destroyPlayer() {
      this.flvPlayer.pause();
      this.flvPlayer.unload();
      this.flvPlayer.detachMediaElement();
      this.flvPlayer.destroy();
      this.flvPlayer = null;
    },

    onError() {
      this.flvPlayer.on(
        flvjs.Events.ERROR,
        (errorType, errorDetail, errorInfo) => {
          console.log("errorType:", errorType);
          console.log("errorDetail:", errorDetail);
          console.log("errorInfo:", errorInfo);
          //视频出错后销毁重新创建
          if (this.flvPlayer) {
            this.destroyPlayer();
            this.createVideo(this.videoUrl, this.idName);
            console.log("断流、出错重启了");
          }
        }
      );
    },
    onInfo() {
      let ths = this;
      this.flvPlayer.on("statistics_info", function (res) {
        if (ths.lastDecodedFrame == 0) {
          ths.lastDecodedFrame = res.decodedFrames;
          return;
        }
        if (ths.lastDecodedFrame != res.decodedFrames) {
          ths.lastDecodedFrame = res.decodedFrames;
        } else {
          ths.lastDecodedFrame = 0;
          if (this.flvPlayer) {
            this.destroyPlayer();
            this.createVideo(this.videoUrl, this.idName);
            console.log("卡死重启了");
          }
        }
      });
    },
    createVideo(url, elementId) {
      if (flvjs.isSupported()) {
        let videoElement = document.getElementById(elementId);
        // if (this.isTalkBack) {
        //   this.flvPlayer = flvjs.createPlayer(
        //     {
        //       type: "flv",
        //       url: url,
        //       isLive: true, //直播模式
        //       hasAudio: true, //视频源只有视频无音频时关掉音频支持
        //       hasVideo: false,
        //     },
        //     {
        //       gop_on: false, //首屏缓冲
        //       enableStashBuffer: false, //播放flv时，设置是否启用播放缓存，只在直播起作用。
        //       enableWorker: false, //浏览器端开启flv.js的worker,多进程运行flv.js
        //       lazyLoad: false,
        //       autoCleanupSourceBuffer: true, //自动清除缓存
        //     }
        //   );
        // } else {
        this.flvPlayer = flvjs.createPlayer(
          {
            type: "flv",
            url: url,
            isLive: true, //直播模式
            hasAudio: false, //视频源只有视频无音频时关掉音频支持
            hasVideo: true,
          },
          {
            gop_on: false, //首屏缓冲
            enableStashBuffer: false, //播放flv时，设置是否启用播放缓存，只在直播起作用。
            enableWorker: false, //浏览器端开启flv.js的worker,多进程运行flv.js
            lazyLoad: false,
            autoCleanupSourceBuffer: true, //自动清除缓存
          }
        );
        // }

        this.flvPlayer.attachMediaElement(videoElement);
        this.flvPlayer.load();
        this.flvPlayer.play();
      }
    },
    setTime() {
      // let arr = new Array(4).fill(0);
      // let num = 0;
      this.flvTimer = setInterval(() => {
        if (this.flvPlayer.buffered.length) {
          let end = this.flvPlayer.buffered.end(0); //获取当前buffered值
          let diff = end - this.flvPlayer.currentTime; //获取buffered与currentTime的差值
          if (diff >= 2.0) {
            //如果差值大于等于2.0秒 手动跳帧 这里可根据自身需求来定
            this.flvPlayer.currentTime = this.flvPlayer.buffered.end(0) - 0.5; //手动跳帧
            console.log("手动帧同步了" + this.flvPlayer.statisticsInfo.url);
            // arr.push(Date.now());
            // num =num+1;
            // arr.shift();
            // //14秒内同步了4次就触发重拉机制
            // //检测频率太高会导致网络较差的情况下播放器转圈
            // if (arr[0]!=0&&arr[3]-arr[0]<=14000){
            //   arr.fill(0);
            //   this.destroyPlayer();
            //   this.createVideo(this.videoUrl, this.idName);
            //   console.log("14秒内帧同步失败已达4次，重启");
            // }
          }
        }
      }, 4000); //4000毫秒执行一次
    },
    setListener() {
      let arrListener = new Array(2).fill(0);
      this.flvListener = setInterval(() => {
        let speed = this.flvPlayer.statisticsInfo.speed;
        //播放器流速度为0时每隔4秒重启一次播放器
        //防止播放器卡死在断流瞬间导致流速度一直不为0
        //播放器错误监听也设为4秒一次，减轻弱网条件下的负载
        if (isNaN(speed) || typeof speed == "undefined" || speed == 0) {
          console.log(speed);
          console.log(arrListener);
          arrListener.fill(0);
          this.destroyPlayer();
          this.createVideo(this.videoUrl, this.idName);
        }
        if (arrListener[0] == arrListener[1] && arrListener[0] != 0) {
          console.log(speed);
          console.log(arrListener);
          arrListener.fill(0);
          this.destroyPlayer();
          this.createVideo(this.videoUrl, this.idName);
        }
        arrListener.push(this.flvPlayer.statisticsInfo.speed);
        arrListener.shift();
      }, 4000); //4秒执行一次
    },
  },
  beforeDestroy() {
    this.destroyPlayer();
    clearInterval(this.flvTimer);
    clearInterval(this.flvListener);
  },
};
</script>
<style scoped lang="scss"></style>
